package com.debao;


import com.debao.common.annotation.Anonymous;
import com.debao.common.constant.WechatConstants;
import com.debao.common.core.domain.AjaxResult;
import com.debao.common.core.domain.entity.SysUser;
import com.debao.common.utils.SecurityUtils;
import com.debao.common.wechat.WechatUtils;
import com.debao.dto.StuReqDto;
import com.debao.system.domain.Coach;
import com.debao.system.domain.UserCard;
import com.debao.system.domain.vo.EditUserReqVo;
import com.debao.system.domain.vo.EnterCoachReqVo;
import com.debao.system.mapper.SysUserMapper;
import com.debao.system.service.*;
import org.slf4j.Logger;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 个人中心
 */
@RestController
@RequestMapping("/api/personal")
public class ApiPersonal {


    @Resource
    private ISysUserService userService;

    @Resource
    private ICoachService coachService;
    @Resource
    private IHarvestAddressService harvestAddressService;

    @Resource
    private IConfigService configService;

    @Resource
    private IUserCardService userCardService;

    @Resource
    private ITimeUserCardService timeUserCardService;

    @Resource
    private IUserCourseCardService userCourseCardService;

    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public AjaxResult getUserInfo() {
        HashMap<String, Object> userInfo = new HashMap<>();
        Long userId = SecurityUtils.getUserId();
        userInfo.put("user", userService.selectUserById(userId));
        // 是否是教练
        Coach coach = coachService.selectCoachByUserId(userId);
        if (coach != null) {
            userInfo.put("coach", coach);
        }
        UserCard userCard = userCardService.selectUserCardByUserId(userId);
        if (userCard != null) {
            userInfo.put("userCard", userCard);
        }
        return AjaxResult.success(userInfo);
    }


    /**
     * 用户信息更新
     *
     * @param vo
     * @return
     */
    @PutMapping("/edit")
    @Anonymous
    public AjaxResult editUser(@RequestBody @Validated EditUserReqVo vo) {
        SysUser user = new SysUser();
        user.setUserId(SecurityUtils.getUserId());
        user.setAvatar(vo.getAvatar());
        user.setNickName(vo.getNickName());
        user.setEmail(vo.getEmail());
        user.setAge(vo.getAge());
        user.setPhonenumber(vo.getPhonenumber());
        user.setSex(vo.getSex());
        String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
        String openId = SecurityUtils.getOpenId();
        WechatUtils.weiXinCheckContent(token, user.getNickName(), openId);
        return AjaxResult.success(userService.updateUser(user));
    }

    /**
     * 教练审核入驻
     *
     * @param vo
     * @return
     */
    @PostMapping("enterCoach")
    public AjaxResult enterCoach(@RequestBody @Valid EnterCoachReqVo vo) {
        Long userId = SecurityUtils.getUserId();
        try {
            int row = coachService.insertCoach(new Coach()
                    .setStadiumId(vo.getStadiumId())
                    .setUserId(userId)
                    .setAvatar(vo.getAvatar())
                    .setIntroduce(vo.getIntroduce())
                    .setMajor(vo.getMajor())
                    .setSkilled(vo.getSkilled())
                    .setStyle(vo.getStyle())
                    .setPrice(vo.getPrice()));
            // 对插入结果进行判断
            if (row == 0) {
                // 这里假设当row为0时，表示插入失败，可能是因为数据重复或其他原因
                return AjaxResult.error("教练入驻申请失败，请联系管理员");
            }
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("系统错误：操作失败");
        }
    }


    /**
     * 获取默认的收货地址信息
     */
    @GetMapping("/defaultAddressInfo")
    public AjaxResult defaultAddressInfo() {
        Long userId = SecurityUtils.getUserId();
        return AjaxResult.success(harvestAddressService.selectDefaultHarvestAddressByUserId(userId));
    }


    /**
     * 课程学员
     */
    @GetMapping("/courseStudent")
    public AjaxResult courseStudent(@Valid StuReqDto dto) {
        // 次卡表
        if (dto.getCourseType() == 1) {
            return AjaxResult.success(timeUserCardService.selectTimeCardStudentList(dto.getCourseId()));
        }
        // 天卡表
        if (dto.getCourseType() == 2) {
            return AjaxResult.success(userCourseCardService.selectUserCardStudentList(dto.getCourseId()));

        }
        return AjaxResult.success(new ArrayList<>());
    }


}
